package com.cabal.common.util;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class CabalGatewayMD5Util {

    private static final int BUFFER_SIZE = 1024;
	
	private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5',
        '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
	

	private CabalGatewayMD5Util() {
	}

	public static String sign(String key, String salt) {
        return DigestUtils.md5Hex(key + salt);
	}

    public static String encodeByMD5(String str,String encode) {
        if (str == null)
            return null;
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.update(str.getBytes(encode));
            return getFormattedText(messageDigest.digest());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String encodeByMD5(String str) {
        if (str == null)
            return null;
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.update(str.getBytes());
            return getFormattedText(messageDigest.digest());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    
    private static String getFormattedText(byte[] bytes) {
        int len = bytes.length;
        StringBuilder buf = new StringBuilder(len * 2);
        // 把密文转换成十六进制的字符串形式
        for (int j = 0; j < len; j++) {
        	buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
            buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
        }
        return buf.toString();
    }

    public static String md5(String plainText) {
        String re_md5 = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes("UTF-8"));
            byte b[] = md.digest();

            int i;

            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }

            re_md5 = buf.toString();

        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return re_md5.toUpperCase();
    }

    public static String sign(String key, String input_charset, String salt) {
        return DigestUtils.md5Hex(getContentBytes(key + salt, input_charset));
    }

    private static byte[] getContentBytes(String content, String charset) {
        if (StringUtils.isNotBlank(charset)) {
            try {
                return content.getBytes(charset);
            } catch (UnsupportedEncodingException var3) {
                throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
            }
        } else {
            return content.getBytes();
        }
    }

    /**
     * 生成32位的MD5签名串
     * @param source 待签名串
     * @param salt 盐
     * @param toUpperCase 是否转大写
     * @return
     */
    public static String md5(String source, String salt, boolean toUpperCase) {
        source = source + salt;

        StringBuilder sb = new StringBuilder(32);

        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] array = md.digest(source.getBytes("utf-8"));

            for (int i = 0; i < array.length; i++) {
                if(toUpperCase) {
                    sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).toUpperCase().substring(1, 3));
                } else {
                    sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1, 3));
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return sb.toString();
    }

    public static String jsonMd5(String jsonParam, String excludeKey, String secretKey) {
        String jsonString = null;
        try {
            jsonString = CabalJsonUtil.getSortedString(jsonParam);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return md5(jsonString, secretKey, false);
    }

    public static String stringParamsMd5(String params, String secretKey) {
        return md5(params, secretKey, false);
    }

    public static String getFileMd5(File file) {
        if (file == null || !file.isFile()) {
            return null;
        }
        MessageDigest digest;
        FileInputStream in;
        byte[] buffer = new byte[BUFFER_SIZE];
        int len;
        try {
            digest = MessageDigest.getInstance("MD5");
            in = new FileInputStream(file);
            while ((len = in.read(buffer, 0, BUFFER_SIZE)) != -1) {
                digest.update(buffer, 0, len);
            }
            in.close();
        } catch (IOException | NoSuchAlgorithmException e) {
            System.out.println(e.getMessage());
            return null;
        }
        BigInteger bigInt = new BigInteger(1, digest.digest());
        String result = bigInt.toString(16);
        if(result.length() < 32) {
            result = "0" + result;
        }
        return result;
    }

    public static void main(String[] args) {
        //System.out.println(CabalGatewayMD5Util.md5("123", "123", false));
        File file = CabalGatewayFileUtil.getLocalFile("cabal/item.enc");
        System.out.println(CabalGatewayMD5Util.getFileMd5(file));
    }
}
